import React from 'react'
import { connect } from 'react-redux'
import classnames from 'classnames'
import './buyStyle.less'

const mapStateToProps = (state) => {
  return {
    // mallItems: state.mall.diamonds,
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    doLoadUserInfo: () => dispatch(global.allActions.appActions.doLoadUserInfo)
  }
}

const Step1 = (props) => {
  const {item = {count: 0, giveAway: 0, goodsName: '钻石', price: 0}, queryInvite, wxPay, inviteId, inviteIdChange, invitePerson = '', tip = ''} = props
  const inviteCn = classnames({'buy-row': true, hide: invitePerson === '' || !(tip === '')})
  const tipCn = classnames({'buy-row': true, hide: tip === ''})
  return <div className="modal-content-wrapper">
    <div className="buy-row first">
      购买商品: <span className="orange-text">{ item.count + item.giveAway } { item.goodsName }</span>
    </div>
    <div className="buy-row">
      购买价格: <span className="orange-text">{ item.price }元</span>
    </div>
    <div className="buy-row clearfix">
      <input type="text" className="invite-id little-larger" value={inviteId} onChange={inviteIdChange} id="invite-ipt" placeholder="请输入邀请人ID"></input>
      {/* <div className="invite-btn">
        <img className="full-width" src="img/mall/dialog/query.png" alt="" onClick={queryInvite}></img>
      </div> */}
    </div>
    <div className={inviteCn}>
      邀请人: <span className="orange-text">{invitePerson}</span>
    </div>
    <div className={tipCn}>
      <span>{tip}</span>
    </div>
    <div className="bottom-btn">
      {/* <img className="full-width" src="img/mall/dialog/wx-pay.png" alt=""></img> */}
      <img onClick={wxPay} className="full-width" src="img/mall/dialog/query.png" alt=""></img>      
    </div>
  </div>
}

const Step2 = (props) => {
  const {invitePerson, inviteId, back, confirm, tip} = props
  const tipCn = classnames({'buy-row': true, hide: tip === ''})
  return <div className="modal-content-wrapper">
    <div className="buy-row first">
      请再次确认邀请人ID无误:
    </div>
    <div className="buy-row larger">ID: <span className="orange-text">{inviteId}</span></div>
    <div className="buy-row larger">昵称: <span className="orange-text">{invitePerson}</span></div>
    <div className={tipCn}>
      <span>{tip}</span>
    </div>
    <div className="bottom-btn">
      <img className="confirm" onClick={back} src="img/mall/dialog/cancel.png" alt=""></img>
      <img className="confirm" onClick={confirm} src="img/mall/dialog/confirm.png" alt=""></img>
    </div>
  </div> 
}

const Step3 = (props) => {
  const {text, confirm} = props
  return <div className="modal-content-wrapper">
  <div className="buy-row first">
    购买钻石成功!
  </div>
  <div className="buy-row"><span>{text}</span></div>
  <div className="bottom-btn">
    <img className="confirm" onClick={confirm} src="img/mall/dialog/confirm.png" alt=""></img>
  </div>
</div> 
}

class BuyDiamond extends React.Component<any, any> {
  public constructor(props) {
    super(props)
    this.state = {
      step: 1,
      inviteId: '',
      invitePerson: '',
      tip: '',
      orderTip: ''
    }
  }
  
  public componentDidMount() {
    const url = `${config.pre}/Order/selectPid/${Cookies.get('areaCode')}`
    const opt = { method: 'GET' }
    fetchJson(url, opt).then(data => {
      console.log('selectPid', data);
      const lastAgent = data.data
      if (lastAgent && this.state.invitePerson === '') {
        this.setState({inviteId: lastAgent.lftid, invitePerson: lastAgent.nickname})
      }
    })
  }

  public focusIpt() {
    if (document.getElementById('invite-ipt')) {
      document.getElementById('invite-ipt').focus()
    }
  }

  public queryInvite(continueBuy: boolean = false) {
    if (this.state.inviteId.length === 0) {
      this.setState({tip: '请输入邀请人ID'})
    } else {
      this.setState({tip: ''})
      const url = `${config.pre}/Order/select/${Cookies.get('areaCode')}/${this.state.inviteId}`
      const opt = { method: 'GET' }
      fetchJson(url, opt).then(data => {
        console.log(data);
        if (data.result) {
          this.setState({tip: data.message, invitePerson: ''})
          return 
        }
        this.setState({tip: '', invitePerson: data.data})
        if (continueBuy) {
          this.setState({step: 2})
        }
      })
    }
  }

  public wxPay() {
    console.log('wxPay');
    const ua = navigator.userAgent
    if (!global.WeixinJSBridge) {
      this.setState({tip: '请在微信内进行购买'})
      return 
    }
    console.log(this.state);
    if (this.state.inviteId === '' && this.state.invitePerson === '') {
      this.setState({tip: '请输入邀请人ID'})
      return 
    }
    this.queryInvite(true)
  }

  public confirm() {
    const params = [{
      gid: this.props.item.gid,
      quantity: 1        
    }]
    const url = `${config.pre}/Order/${Cookies.get('areaCode')}/${this.state.inviteId}`
    const opt = { method: 'POST', body: JSON.stringify(params)}
    fetchJson(url, opt).then(data => {
      if (data.result) {
        this.setState({orderTip: '生成订单失败,' + data.message})
        return
      }
      this.setState({orderTip: ''})
      this.onBridgeReady(data.data)
    })
  }

  onBridgeReady(data) {
    const { item } = this.props
    const onComplete = res => {
      if (res.err_msg === 'get_brand_wcpay_request:ok') {
        let infoText = item.giveAway ? `已购买钻石${item.count}个, 赠送${item.giveAway}个`
          : `已购买钻石${item.count}个`
        this.props.doLoadUserInfo()
        this.setState({tip: infoText, step: 3})
      } else {
        this.setState({tip: '支付失败: ' + res.err_msg + ',' + JSON.stringify(res)})
      }
    }
    WeixinJSBridge.invoke('getBrandWCPayRequest', data, onComplete)
  }

  public handleInviteIdChange(e) {
    const parsed = e.target.value.match(/[0-9]?/g)
    if (parsed.length <= 7) {
      this.setState({inviteId: parsed.join('')})
    }
  }

  public render() {
    const {close, item} = this.props
    const {step, inviteId, invitePerson, tip, orderTip} = this.state
    return <div className="dialog-block has-mask full">
      <div className="mall-content content">
        <div className="full-width title-wrapper">
          <img onClick={close} className="close" src="img/mall/dialog/close.png" alt=""/>
          <img className="title" src="img/mall/dialog/text-buy.png" alt=""/>
        </div>
        <div className="modal-wrapper">
          {step === 1 ? <Step1 item={item} inviteId={inviteId} invitePerson={invitePerson} tip={tip}
            queryInvite={this.queryInvite.bind(this)}
            wxPay={this.wxPay.bind(this)}
            inviteIdChange={this.handleInviteIdChange.bind(this)}></Step1> : null}
          {step === 2 ? <Step2 inviteId={inviteId}
           invitePerson={invitePerson}
           tip={orderTip}
           back={() => this.setState({step: 1, orderTip: ''})}
           confirm={this.confirm.bind(this)}></Step2> : null}
          {step === 3 ? <Step3 text={tip} confirm={close}></Step3> : null}
        </div>
      </div>
    </div>
  }

}
export default connect(mapStateToProps, mapDispatchToProps)(BuyDiamond)